import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp();
Page({
  data: {
    defaultData: {
      title: "方案配置", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    phoneNumber: null, //联系方式
    newRoomName: '', // 新房间名称
    showAddRoomDialog: false, // 控制增加房间的对话框显示
    selectedAddress: '', //选择的地址信息
    fullAddress: "", //地址
    showPosition: false, //位置
    locationAll: [], //安装位置
    MyLocations: [], // 私有位置列表
    PublicLocations: [], // 公共位置列表
    isPublicSelected: null, // 默认选中公共位置
    locationName: "选择位置",
    checked: false,
    roomId: null,
    roomList: {},
    fileList: [], //图片上传
    selectRoom: false,
    get: false,
    radio: '1',
    programme: {},
    isProgrammeUpdated: false,
    keyboardHeight: 0,
    scrollTop: 0,
    saveHouse: {},
    isUploading: true,
    selectedHouseType: {},
    showHouseType: false,
    MyHouseData: [],
    pgeName: "",
    getSysDicKey: "",
    productDiscountOptions: [], // 存储商品折扣数据
    serviceDiscountOptions: [], // 存储服务折扣数据
    discountOptions: [],
    showDiscount: false,
    priceDiscountPdt: "无",
    priceDiscountSev: "无",
    discountProductRadio: null,
    discountServiceRadio: null,
    isDiscountProduct: false,
    showMyPosition: false,
    showAddMyLocationDialog: false,
    newMyLocationName: "",
  },

  onLoad(options) {
    console.log("----------------");
    // 监听键盘高度变化
    wx.onKeyboardHeightChange((res) => {
      if (res.height > 0) {
        this.setData({
          keyboardHeight: res.height
        });
      } else {
        this.setData({
          keyboardHeight: 0
        });
      }
    });


    if (options.programme) {
      console.log("====================");
      const programmeDate = JSON.parse(decodeURIComponent(options.programme));
      const priceModel = programmeDate.priceModel;

      this.setData({
        programme: programmeDate,
        radio: priceModel !== null ? priceModel.toString() : "1"
      });

      console.log("Before selectedHouse:", this.data.programme);
      console.log("options.programme", programmeDate);

      this.selectedHouse();
    }

    if (this.data.programme.priceDiscountPdt !== null) {
      this.setData({
        discountProductRadio: this.data.programme.priceDiscountPdt
      })
      console.log("this.data.discountProductRadio", this.data.discountProductRadio);
    }
    if (this.data.programme.priceDiscountSev !== null) {
      this.setData({
        discountServiceRadio: this.data.programme.priceDiscountSev
      })
      console.log("this.data.discountServiceRadio", this.data.discountServiceRadio);
    }


    this.getCustomPrice()

  },

  onShow() {
    console.log("+++++++++", this.data.programme.roomEntityList);
    if (app.globalData.isUploading) {
      console.log("================", this.data.programme.roomEntityList.length);
      console.log("=====", this.data.programme.roomEntityList);
      // this.getLocationAll()
      this.getMyLocations()
      this.getProductLocationAll()
      // 读取通过缓存传递的数据
      if (wx.getStorageSync('selectedHouseType')) {
        console.log();
        const selectedHouseType = wx.getStorageSync('selectedHouseType');
        try {
          const parsedHouseType = JSON.parse(selectedHouseType);
          console.log("Parsed selectedHouseType:", parsedHouseType);
          this.setData({
            selectedHouseType: parsedHouseType
          }, () => {
            this.importHouse();
            console.log("==+++++++===", this.data.programme.roomEntityList);
            wx.removeStorageSync('selectedHouseType'); // 延迟清除缓存
          });
        } catch (error) {
          console.error("Error parsing selectedHouseType:", error);
        }


        console.log("selectedHouseType", this.data.selectedHouseType);
        console.log("=====", this.data.programme.roomEntityList);
        // 清除缓存的数据
      }

      if (this.data.get) {
        this.getAddress();
      }

      this.getHouseType()
      console.log("fderfger");
    }
  },

  // 私有位置弹框
  showPublicPosition() {
    this.setData({
      showMyPosition: true
    });
  },

  // 获取私有位置
  async getMyLocations() {
    const pageNum = 1
    const pageSize = 1000
    try {
      const res = await request({
        url: indexApi.getMyLocationsApi(pageNum, pageSize),
        data: {}
      });
      this.setData({
        MyLocations: res.data.records
      })
      console.log("私有位置", this.data.MyLocations);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 删除私有位置
  delMyLocation(event) {
    console.log("删除私有位置", event);
    const mylocationitem = event.currentTarget.dataset.mylocationitem

    // // 弹出确认框
    Dialog.confirm({
        title: '确定要删除此位置吗',
        zIndex: 9999
      })
      .then(() => {
        this.delLocation(mylocationitem)
      }).catch(() => {
        // 取消删除的逻辑
        console.log('取消删除');
      });
  },

  async delLocation(item) {
    const mylocationitem = item
    mylocationitem.isDel = 1
    try {
      const res = await request({
        url: indexApi.delMyLocationApi(),
        method: "POST",
        data: mylocationitem
      });
      if (res.code == 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
        });
      }
      this.getMyLocations()
      console.log("删除私有位置", res);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //增加私有位置
  showAddMyLocation() {
    this.setData({
      showAddMyLocationDialog: true,
      newMyLocationName:""
    })
  },

  //修改私有位置
  changeMyLocation(event) {
    const myLocationsItem = event.currentTarget.dataset.mylocationsitem;
    this.setData({
      showAddMyLocationDialog: true,
      newMyLocationName: myLocationsItem.title,
      editLocationId: myLocationsItem.id // 保存id用于后续判断
    });
    console.log("修改的私有位置", this.data.newMyLocationName, this.data.editLocationId);
  },

  //确定私有位置
  beSureMyLocation() {
    this.setData({
      showMyPosition: false
    })
  },

  // 输入新增的私有位置
  addMyLocationChange(event) {
    this.setData({
      newMyLocationName: event.detail
    });
    console.log("输入新增的私有位置", this.data.newMyLocationName);
  },

  // 确认增加私有位置
  async onConfirmAddMyLocation() {
    const title = this.data.newMyLocationName;
    const id = this.data.editLocationId; // 获取id
    if (!title.trim()) {
      wx.showToast({
        title: '位置名称不能为空',
        icon: 'none'
      });
      return;
    }

    console.log("+++++++++++++++++++", title);

    try {
      const data = {
        title
      };
      // 如果是修改，传递id
      if (id) {
        data.id = id;
      }
      const res = await request({
        url: indexApi.saveMyLocationApi(),
        method: "POST",
        data
      });
      this.getMyLocations()
      console.log("保存私有位置", this.data.MyLocations);
      wx.showToast({
        title: id ? "修改成功" : "增加成功", // 根据是否有id判断是修改还是新增
        icon: "none",
      });
  
    } catch (error) {
      console.error("Error:", error);
    }

  },

  

  //商品折扣
  productDiscount() {
    this.setData({
      getSysDicKey: "PRODUCT_DISCOUNT",
      isDiscountProduct: false,
      showDiscount: true
    })
    console.log("discountProductRadio", this.data.discountProductRadio);
    this.getLocationAll()
  },

  //服务折扣
  serviceDiscount() {
    this.setData({
      getSysDicKey: "SERVICE_DISCOUNT",
      isDiscountProduct: true,
      showDiscount: true
    })
    console.log("discountServiceRadio", this.data.discountServiceRadio);
    this.getLocationAll()
  },

  // 选择折扣
  onDiscountChange(event) {
    console.log("event", event.target.dataset.discountitem);
    const discount = event.target.dataset.discountitem.code
    if (this.data.getSysDicKey == "PRODUCT_DISCOUNT") {
      this.setData({
        discountProductRadio: event.detail,
        showDiscount: false,
        priceDiscountPdt: discount,
        "programme.priceDiscountPdt": discount,
        "programme.priceDiscountProduct": event.target.dataset.discountitem,
      })
      console.log("priceDiscountPdt", event.target.dataset.discountitem.code);
    } else {
      this.setData({
        discountServiceRadio: event.detail,
        showDiscount: false,
        priceDiscountSev: discount,
        "programme.priceDiscountSev": discount,
        "programme.priceDiscountService": event.target.dataset.discountitem,
      })
    }

    console.log("方案的折扣", this.data.programme);
  },

  //公共位置
  async getProductLocationAll() {
    try {
      const res = await request({
        url: indexApi.getProductLocationAllApi(),
        data: {}
      });
      this.setData({
        PublicLocations: res.data.records
      })
      console.log("安装公共位置", this.data.PublicLocations);
    } catch (error) {
      console.error("Error:", error);
    }
  },


  // 安装位置,商品折扣,服务折扣
  async getLocationAll() {
    try {
      let a = this.data.getSysDicKey;
      const res = await request({
        url: indexApi.getSysDicApi(a),
        data: {}
      });
      if (a == "PRODUCT_DISCOUNT") {
        this.setData({
          productDiscountOptions: res.data,
          discountOptions: res.data,
        })
        console.log("商品折扣", this.data.discountOptions);
      } else if (a == "SERVICE_DISCOUNT") {
        this.setData({
          serviceDiscountOptions: res.data,
          discountOptions: res.data,

        })
        console.log("服务折扣", this.data.serviceDiscountOptions);
        console.log("折扣弹框", this.data.showDiscount);
      }
      console.log("22222222222222222222222", this.data.programme);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //清空折扣
  emptyPdt() {
    // priceDiscountPdt: "无",
    // priceDiscountSev: "无",
    // discountProductRadio: null,
    // discountServiceRadio: null,
    this.setData({
      'programme.priceDiscountPdt': null,
      priceDiscountPdt: "无",
      discountProductRadio: null,
    })

    console.log("清空商品折扣", this.data.programme);
    console.log("priceDiscountPdt", this.data.priceDiscountPdt);
  },
  emptySev() {
    this.setData({
      'programme.priceDiscountSev': null,
      priceDiscountSev: "无",
      discountServiceRadio: null,
    })
    console.log("清空折扣");
  },


  // 自定义价格体系
  async getCustomPrice() {
    try {
      const res = await request({
        url: indexApi.getCustomPriceApi(),
        data: {}
      });
      console.log("res", res.data);
    } catch (error) {
      console.error("Error:", error);
    }
  },


  onChange(event) {
    this.setData({
      radio: event.detail,
      "programme.priceModel": event.detail
    });
    console.log("programme.priceModel", this.data.programme);
  },

  toProduct() {
    const {
      programme
    } = this.data
    // if (this.data.radio == 2) {
    const serviceType = app.globalData.serviceType;
    const serviceTypeStr = encodeURIComponent(JSON.stringify(serviceType));
    console.log("serviceTypeStr", serviceTypeStr);
    const fromPage = 2;
    console.log("--------------", programme);
    wx.setStorageSync('programmeData', programme);
    wx.navigateTo({
      url: `/packageOrder/pages/product/index?serviceTypeName=${serviceTypeStr}&fromPage=${fromPage}&programme=${programme}`,
    });
    // } else {
    //   wx.showToast({
    //     title: '请选择私有价格体系',
    //     icon: 'none',
    //   });
    // }
  },

  beforeRead() {
    app.globalData.isUploading = false
    console.log("beforeRead", app.globalData.isUploading);
  },

  //上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    console.log("filegerger", file);
    app.globalData.isUploading = false
    console.log("afterRead", app.globalData.isUploading);
    this.uploadFile(file);
  },
  onOversize(event) {
    wx.showToast({
      title: '文件大小超出限制',
      icon: 'none'
    });
  },

  async uploadFile(file) {
    app.globalData.isUploading = false
    console.log("uploadFile", app.globalData.isUploading);
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log("图片地址",data);
          file.url = data.data;
          this.setData({
            fileList: [...this.data.fileList, file],
          });
          console.log("fileList", this.data.fileList);
        },
        fail: (err) => {
          console.error('Upload failed', err);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
      });
    } catch (error) {
      console.error("Error:", error);
    } finally {
      app.globalData.isUploading = true
      console.log("app.globalData.isUploading", app.globalData.isUploading);
    }
  },


  onFocus(e) {
    const query = wx.createSelectorQuery();
    query.select('#feedback-textarea').boundingClientRect((rect) => {
      wx.pageScrollTo({
        scrollTop: rect.top + this.data.scrollTop - this.data.keyboardHeight,
        duration: 300
      });
    }).exec();
  },

  onBlur() {
    this.setData({
      keyboardHeight: 0
    });
  },

  // 户型配置备注
  onInputRemark(e) {
    this.setData({
      inputValue: e.detail.value
    });
    this.setData({
      'programme.remark': e.detail.value
    })
    console.log("户型备注", this.data.programme);
  },

  // selectedHouse() {
  //   const programmeCopy = JSON.parse(JSON.stringify(app.globalData.programme));
  //   this.setData({
  //     programme: programmeCopy,
  //     selectRoom: true
  //   });
  //   console.log("从快速下单来的方案", this.data.programme);
  //   this.defaultFloorImage()
  // },
  selectedHouse() {
    // console.log("programmeFromUrl", programmeFromUrl);
    this.setData({
      // programme: programmeFromUrl,
      selectRoom: true
    });
    console.log("从快速下单来的方案", this.data.programme);
    this.defaultFloorImage()
  },

  importHouse() {
    console.log("Initial this.data.programme.roomEntityList", this.data.programme.roomEntityList);

    // 深拷贝
    const programmeRooms = JSON.parse(JSON.stringify(this.data.programme.roomEntityList.filter(room => room.isDel !== 1)));
    console.log("Deep copied programmeRooms before any operation:", programmeRooms);

    const selectedHouse = this.data.selectedHouseType;
    console.log("this.data.selectedHouseType", selectedHouse);

    if (selectedHouse && selectedHouse.rooms && Array.isArray(selectedHouse.rooms)) {
      const selectedRooms = selectedHouse.rooms;
      console.log("Selected rooms:", selectedRooms);

      const selectedRoomCount = selectedRooms.length;
      const programmeRoomCount = programmeRooms.length;

      if (selectedRoomCount > programmeRoomCount) {
        // 添加新房间到 programmeRooms
        for (let i = 0; i < programmeRoomCount; i++) {
          programmeRooms[i].roomName = selectedRooms[i].roomName;
          programmeRooms[i].roomLocation = selectedRooms[i].roomLocation;
        }

        for (let i = programmeRoomCount; i < selectedRoomCount; i++) {
          const newRoom = {
            ...selectedRooms[i],
            productCount: 0,
            productTypeNum: 0,
            roomProductEntityList: [],
            roomProductList: [],
          };
          programmeRooms.push(newRoom);
        }
      } else if (selectedRoomCount < programmeRoomCount) {
        // 更新现有房间并删除多余的房间
        for (let i = 0; i < selectedRoomCount; i++) {
          programmeRooms[i].roomName = selectedRooms[i].roomName;
          programmeRooms[i].roomLocation = selectedRooms[i].roomLocation;
        }

        for (let i = selectedRoomCount; i < programmeRoomCount; i++) {
          const room = programmeRooms[i];
          if (room && !room.id) {
            programmeRooms.splice(i, 1);
            i--;
          } else if (room && room.id) {
            room.isDel = 1;
          }
        }
      } else if (selectedRoomCount === programmeRoomCount) {
        // 房间数量相等，直接更新
        for (let i = 0; i < selectedRoomCount; i++) {
          programmeRooms[i].roomName = selectedRooms[i].roomName;
          programmeRooms[i].roomLocation = selectedRooms[i].roomLocation;
        }
      }

      console.log("Modified programmeRooms before setData:", programmeRooms);

      // 更新数据并确保 setData 完成后打印
      this.setData({
        programme: {
          ...this.data.programme,
          roomEntityList: programmeRooms,
          houseTypeItemId: selectedHouse.id,
          houseName: selectedHouse.houseName,
          imgUrl: selectedHouse.imgUrl,
          remark: selectedHouse.remark
        }
      }, () => {
        console.log("Data has been set - programme.roomEntityList", this.data.programme.roomEntityList);
        this.defaultFloorImage(); // 依赖于 programme.roomEntityList 的其他操作放在这里
      });
    }
  },

  /// 获取导入的户型
  // importHouse() {
  //   const selectedHouse = app.globalData.selectedHouseType;
  //   console.log("app.globalData.selectedHouseType",app.globalData.selectedHouseType);
  //   // 遍历每个房间并添加新的属性
  //   if (selectedHouse && selectedHouse.rooms && Array.isArray(selectedHouse.rooms)) {
  //     selectedHouse.rooms = selectedHouse.rooms.map(room => {
  //       return {
  //         ...room,
  //         productCount: 0,
  //         productTypeNum: 0,
  //         roomProductEntityList: [],
  //         roomProductList: [], // 初始化为一个空数组
  //       };
  //     });
  //   }
  //   console.log("this.data.selectedHouse", selectedHouse);
  //   console.log("roomList==============", this.data.programme);
  //   const programme = this.data.programme
  //   programme.roomEntityList=selectedHouse.rooms
  //   programme.houseTypeItemId=selectedHouse.id
  //   programme.houseName=selectedHouse.houseName
  //   // 更新programme中的房间列表
  //   this.setData({
  //     programme:programme
  //   });

  //   console.log("Updated roomList:", this.data.programme);
  // },


  //选择地址
  selectAddress() {
    this.setData({
      get: true,
      isProgrammeUpdated: true,
    })
    wx.navigateTo({
      url: '/packageUserCenter/pages/address/index?fromPage=1',
    })
  },

  // 客户信息地址
  getAddress() {
    const programme = this.data.programme;
    const selectedAddress = app.globalData.selectedAddress;
    programme.addressEntity = selectedAddress;
    programme.addressId = selectedAddress.addressId;
    this.setData({
      programme: programme
    });
  },

  // 显示增加房间的输入框
  showAddRoomDialog() {
    this.setData({
      showAddRoomDialog: true,
      isProgrammeUpdated: false,
    });
  },

  // 关闭增加房间和位置的对话框
  onClose() {
    this.setData({
      showAddRoomDialog: false,
      showAddMyLocationDialog: false
    });
  },

  // 处理输入框变化
  onInputChange(event) {
    this.setData({
      newRoomName: event.detail
    });
  },

  // 确认增加房间
  onConfirmAddRoom() {
    const newRoomName = this.data.newRoomName;
    if (!newRoomName.trim()) {
      wx.showToast({
        title: '房间名称不能为空',
        icon: 'none'
      });
      return;
    }

    const newRoom = {
      tid: this.data.programme.roomEntityList.length,
      roomName: newRoomName,
      productCount: 0,
      productTypeNum: 0,
      isDel: 0,
      roomProductEntityList: [],
      roomLocation: "",
      roomProductList: [],
    };
    this.setData({
      'programme.roomEntityList': [...this.data.programme.roomEntityList, newRoom],
      showAddRoomDialog: false,
      newRoomName: ''
    });
    wx.showToast({
      title: "增加成功",
      icon: "none",
    });
    console.log("新增房间位置", this.data.programme);
  },

  // 删除房间
  deleteItem(event) {
    const tid = event.currentTarget.dataset.tid;
    const activeRooms = this.data.programme.roomEntityList.filter(item => item.isDel !== 1);
    if (activeRooms.length === 1) {
      wx.showToast({
        title: '最后一个房间不能删除',
        icon: 'none'
      });
      return;
    }

    // 弹出确认框
    Dialog.confirm({
        title: '确定要删除此房间吗',
      })
      .then(() => {
        const updatedRooms = this.data.programme.roomEntityList.map(item => {
          if (item.tid == tid) {
            return {
              ...item,
              isDel: 1
            };
          }
          return item;
        });
        this.setData({
          "programme.roomEntityList": updatedRooms,
        });

        console.log("programme", this.data.programme);
      }).catch(() => {
        // 取消删除的逻辑
        console.log('取消删除');
      });
  },


  changeInput(event) {
    const tid = event.currentTarget.dataset.tid;
    const newRoomName = event.detail.value;

    const updatedRooms = this.data.programme.roomEntityList.map(item => {
      if (item.tid === tid) {
        return {
          ...item,
          roomName: newRoomName
        };
      }
      return item;
    });

    this.setData({
      "programme.roomEntityList": updatedRooms,
    });
  },

  confirmCloseRoom() {
    const app = getApp();
    app.globalData.programme = this.data.programme;
    app.globalData.importHouse = true

    wx.switchTab({
      url: '/pages/quick/index',
    })
  },
  //返回到快速下单
  backQuick() {
    wx.switchTab({
      url: '/pages/quick/index?fromRoom=true',
    })
  },

  //公共位置
  showPublicLocations() {
    this.setData({
      locationAll: this.data.PublicLocations,
      isPublicSelected: true
    })
    this.showPositionChange()
    console.log("切换共有位置", this.data.locationAll);
  },
  //私有位置
  showPrivateLocations() {
    this.setData({
      locationAll: this.data.MyLocations,
      isPublicSelected: false
    })
    this.showPositionChange()
    console.log("切换私有位置", this.data.locationAll);
  },


  // 点击位置弹框
  showPositionChange(event) {
    const {
      programme,
      // locationAll,
      // PublicLocations
    } = this.data;
    if (this.data.isPublicSelected == null) {
      this.setData({
        locationAll: this.data.PublicLocations,
        isPublicSelected: true
      })
    }
    // this.setData({
    //   locationAll:this.data.PublicLocations
    // })
    console.log("点击位置弹框", this.data.locationAll);
    const locationAll = this.data.locationAll
    if (event) {
      const selectRoomId = event.currentTarget.dataset.roomid;
      this.setData({
        showPosition: true,
        roomId: selectRoomId
      });
    }
    const roomId=this.data.roomId
   
    const currentRoom = programme.roomEntityList.find(room => room.tid == roomId);
    if (currentRoom) {
      if (currentRoom.roomLocation) {
        const roomLocationCodes = currentRoom.roomLocation.split(',').map(id => Number(id.trim()));
        console.log("roomLocationCodes", roomLocationCodes);
        const updatedLocationAll = locationAll.map(position => ({
          ...position,
          checked: roomLocationCodes.includes(position.id)
        }));

        this.setData({
          locationAll: updatedLocationAll,
        });
      }
    }
    console.log("+===================", this.data.locationAll);

  },

  closePosition() {
    this.setData({
      showPosition: false,
      showDiscount: false,
      // showMyPosition: false,
      isPublicSelected: null
    })
  },


  // 选择位置
  positionChange(event) {
    const {
      id
    } = event.currentTarget.dataset;
    const {
      programme,
      roomId,
      locationAll
    } = this.data;

    if (!locationAll) {
      console.error("locationAll is undefined");
      return;
    }

    const updatedLocationAll = locationAll.map(position => {
      if (position.id === id) {
        return {
          ...position,
          checked: !position.checked
        };
      }
      return position;
    });

    const updatedRooms = programme.roomEntityList.map(room => {
      if (room.tid === roomId) {
        let roomLocation = room.roomLocation ? room.roomLocation.split(',') : [];
        if (roomLocation.includes(id)) {
          roomLocation = roomLocation.filter(locCode => locCode !== id);
        } else {
          roomLocation.push(id);
        }
        roomLocation = roomLocation.join(',');

        return {
          ...room,
          roomLocation: roomLocation
        };
      }
      return room;
    });

    this.setData({
      'programme.roomEntityList': updatedRooms,
      locationAll: updatedLocationAll
    });
    console.log("方案里面的安装位置", this.data.programme);
  },

  //获取默认户型图
  defaultFloorImage() {
    if (this.data.programme.imgUrl || this.data.programme.houseTypeItem) {
      console.log("defaultFloorImage", this.data.programme.imgUrl);
      console.log("fileList", this.data.fileList);

      this.setData({
        fileList: [{
          tempFilePath: this.data.programme.imgUrl || this.data.programme.houseTypeItem.imgUrl,
          size: 4836037,
          fileType: "image",
          type: "image",
          url: this.data.programme.imgUrl || this.data.programme.houseTypeItem.imgUrl,
          thumb: this.data.programme.imgUrl || this.data.programme.houseTypeItem.imgUrl
        }]
      });
      // this.afterRead(this.data.fileImage)
      console.log("有没有", this.data.fileList);
    }

  },


  // 删除图片
  onDelete(event) {
    const {
      index
    } = event.detail;
    const {
      fileList
    } = this.data;

    fileList.splice(index, 1);
    this.setData({
      fileList
    });
  },

  toProgramme() {
    const programme = JSON.stringify(this.data.programme);
    wx.navigateTo({
      url: `/packageOrder/pages/programme/index?programme=${encodeURIComponent(programme)}`,
    });
  },



  saveHouseType() {
    this.setData({
      showHouseType: true
    })
  },

  houseTypeNameChange(e) {
    this.setData({
      pgeName: e.detail
    });
  },


  // 确认户型名称
  onConfirmHouseTypeName() {
    const {
      pgeName,
      MyHouseData
    } = this.data;

    if (pgeName.trim() === "") {
      wx.showToast({
        title: "请输入户型名",
        icon: "none",
      });
      return;
    }
    // 检查名称是否已经存在
    const existingHouse = MyHouseData.find(house => house.houseName === pgeName);
    console.log("existingHouse", existingHouse);
    if (existingHouse) {
      wx.showModal({
        title: '提示',
        content: '该户型名称已存在，是否覆盖？',
        success: (res) => {
          if (res.confirm) {
            this.saveMyHouseType(existingHouse.id);
          } else {
            this.setData({
              showHouseType: true,
              pgeName: ''
            });
          }
        }
      });
    } else {
      this.saveMyHouseType();
    }
  },

  //储存户型
  async saveMyHouseType(houseId = null) {
    this.saveMyHouseData(houseId)
    let houseTypeItemEntity = {}
    houseTypeItemEntity = this.data.saveHouse
    try {
      const res = await request({
        url: indexApi.saveMyHouseApi(),
        method: "POST",
        data: houseTypeItemEntity
      });
      wx.showToast({
        title: "储存户型成功",
        icon: "none",
      });
      this.setData({
        selectedHouseType: res.data
      }, () => {
        this.importHouse();
        this.getHouseType()
      });
      console.log("储存户型", res);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  async getHouseType() {
    let id = -1;
    try {
      const res = await request({
        url: indexApi.getHouseTypeApi(),
        method: "POST",
        data: {
          id: id
        }
      });
      this.setData({
        MyHouseData: res.data
      })
      console.log("我的户型", this.data.MyHouseData);
    } catch (error) {
      console.error("Error:", error);
    }
  },


  // 拼接户型数据
  saveMyHouseData(houseId = null) {
    const {
      programme,
      MyHouseData,
      pgeName
    } = this.data;
    console.log("programme", programme);
    console.log("houseId", houseId);

    const existingHouse = MyHouseData.find(house => house.houseName === pgeName);
    console.log("existingHouse", existingHouse);
    const houseName = this.data.pgeName;

    if (existingHouse !== undefined) {
      let filteredRooms = programme.roomEntityList.filter(room => room.isDel !== 1);
      console.log("filteredRooms", filteredRooms);

      if (existingHouse && existingHouse.rooms) {
        existingHouse.rooms = existingHouse.rooms.map(existingRoom => {
          const match = filteredRooms.find(room => room.roomName === existingRoom.roomName);
          if (!match) {
            return {
              ...existingRoom,
              isDel: 1
            };
          }
          return existingRoom;
        });

        filteredRooms.forEach(room => {
          const match = existingHouse.rooms.find(existingRoom => existingRoom.roomName === room.roomName);
          if (!match) {
            existingHouse.rooms.push(room);
          }
        });
      } else {
        existingHouse.rooms = filteredRooms;
      }

      console.log("updated existingHouse rooms", existingHouse.rooms);
      const roomNames = existingHouse.rooms.map(room => room.roomName).join(',');
      const remark = programme.remark;

      // 创建保存的户型数据结构
      const saveHouse = {
        houseName,
        roomNames,
        remark,
        imgUrl: this.data.fileList[0].url,
        rooms: existingHouse.rooms
      };

      if (houseId) {
        saveHouse.id = houseId;
      }

      this.setData({
        saveHouse: saveHouse
      });

      console.log("拼接数据结构", saveHouse);
    } else {
      const roomNames = programme.roomEntityList
        .filter(room => room.isDel !== 1)
        .map(room => room.roomName)
        .join(',');

      const remark = programme.remark;

      const rooms = programme.roomEntityList
        .filter(room => room.isDel !== 1)
        .map(room => {
          return {
            roomName: room.roomName,
            floorCode: room.floorCode || "",
            remark: room.remark || "",
            roomLocation: room.roomLocation
          };
        });

      const saveHouse = {
        houseName,
        roomNames,
        remark,
        imgUrl: this.data.fileList[0].url,
        rooms
      };

      this.setData({
        saveHouse: saveHouse
      });

      console.log("拼接数据结构", saveHouse);

    }
  },




  //输入户型名
  onHouseNameInput(e) {
    this.setData({
      'programme.houseName': e.detail.value
    });
    console.log("输入户型名", this.data.programme);
  }


});